

package com.zdkj.subway.stm.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.admin.api.entity.SysDictItem;
import com.zdkj.common.core.constant.CommonConstants;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.stm.constant.StmConstans;
import com.zdkj.subway.stm.dto.in.SwStTvmDailyBillDTO;
import com.zdkj.subway.stm.entity.SwStTvmDailyBill;
import com.zdkj.subway.stm.fegin.SystemUserService;
import com.zdkj.subway.stm.service.SwStTvmDailyBillService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * TVM日结账单录入
 *
 * @author songtuo
 * @date 2020-03-06 13:50:10
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swsttvmdailybill")
@Api(value = "swsttvmdailybill", tags = "TVM日结账单录入管理")
@Slf4j
public class SwStTvmDailyBillController {

    private final SwStTvmDailyBillService swStTvmDailyBillService;

    private final SystemUserService systemUserService;

    /**
     * 分页查询
     *
     * @param page             分页对象
     * @param swStTvmDailyBill TVM日结账单录入
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwStTvmDailyBillPage(Page page, SwStTvmDailyBill swStTvmDailyBill) {
//        SwStTvmDailyBill swStTvmDailyBillObj = ObjectUtils.getDefaultObj(SwStTvmDailyBill.class);
//        swStTvmDailyBill.setLineCode(swStTvmDailyBillObj.getLineCode());
//        swStTvmDailyBill.setStationCode(swStTvmDailyBillObj.getStationCode());
        QueryWrapper<SwStTvmDailyBill> queryWrapper = Wrappers.query(swStTvmDailyBill);
        String dateCondition = swStTvmDailyBill.getStartTimeDTO();
        String dateConditions = swStTvmDailyBill.getEndTimeDTO();
        if (StringUtils.isNotBlank(dateCondition)) {
            queryWrapper.lambda().likeRight(SwStTvmDailyBill::getStartTime, dateCondition);
        }
        if (StringUtils.isNotBlank(dateConditions)) {
            queryWrapper.lambda().likeRight(SwStTvmDailyBill::getEndTime, dateConditions);
        }
        queryWrapper.orderByDesc("-APPROVAL_STATUS","START_TIME","END_TIME","TVM_CODE");
        if (!SecurityUtils.getUser().getBelongToLine()) {
            queryWrapper.eq("line_code", SecurityUtils.getUser().getLineCode());
            queryWrapper.eq("station_code", SecurityUtils.getUser().getStationCode());
            return R.ok(swStTvmDailyBillService.page(page, queryWrapper));
        } else {
            return R.ok(swStTvmDailyBillService.page(page, queryWrapper));
        }
    }

    /**
     * 通过id查询TVM日结账单录入
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swStTvmDailyBillService.getById(id));
    }

    /**
     * 新增TVM日结账单录入
     *
     * @param stTvmDailyBillDTO TVM日结账单录入
     * @return R
     */
    @ApiOperation(value = "新增TVM日结账单录入", notes = "新增TVM日结账单录入")
    @SysLog("新增TVM日结账单录入")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('swsttvmdailybill_add')")
    public R save(@RequestBody SwStTvmDailyBillDTO stTvmDailyBillDTO) {
        return R.ok(swStTvmDailyBillService.saveSwStTvmDailyBill(stTvmDailyBillDTO));
    }

    /**
     * 修改TVM日结账单录入
     *
     * @param swStTvmDailyBillDTO TVM日结账单录入
     * @return R
     */
    @ApiOperation(value = "修改TVM日结账单录入", notes = "修改TVM日结账单录入")
    @SysLog("修改TVM日结账单录入")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('swsttvmdailybill_edit')")
    public R updateById(@RequestBody SwStTvmDailyBillDTO swStTvmDailyBillDTO) {
        return R.ok(swStTvmDailyBillService.updateSwStTvmDailyBill(swStTvmDailyBillDTO));
    }

    /**
     * 通过id删除TVM日结账单录入
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除TVM日结账单录入", notes = "通过id删除TVM日结账单录入")
    @SysLog("通过id删除TVM日结账单录入")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('swsttvmdailybill_del')")
    public R removeById(@PathVariable Integer id) {
        return R.ok(swStTvmDailyBillService.deleteCascadeById(id));
    }

    /**
     * 查询日结账单详情
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询TVM日结账单详情", notes = "通过id查询")
    @GetMapping("/details/{id}")
    public R getSwTvmCheckDetails(@PathVariable("id") Integer id) {
        return R.ok(swStTvmDailyBillService.queryDetailsByid(id));
    }


    /**
     * 批量删除子表
     *
     * @param idList
     * @return
     */
    @SysLog("通过id批量删除TVM日结账单录入")
    @DeleteMapping("/batchCascadeDel")
    @PreAuthorize("@pms.hasPermission('swsttvmdailybill_batch_del')")
    @Transactional
    @ApiOperation(value = "通过id批量删除TVM日结账单录入", notes = "通过id批量删除TVM日结账单录入")
    public R batchRemoveById(@RequestBody List<Integer> idList) {
        List<SwStTvmDailyBill> list = swStTvmDailyBillService.list(new QueryWrapper<SwStTvmDailyBill>().lambda().in(SwStTvmDailyBill::getId, idList));
        List<Integer> deleteIds = list.stream().filter(x -> !x.getApprovalStatus().equals(CommonConstants.SUBMIT)).map(x -> x.getId()).collect(Collectors.toList());
        deleteIds.forEach(swStTvmDailyBillService::deleteCascadeById);
        return R.ok();
    }

    @GetMapping("/export")
    public void export(Page page, SwStTvmDailyBill swStTvmDailyBill, HttpServletResponse response) {
        List<SwStTvmDailyBill> records = swStTvmDailyBillService.page(page, Wrappers.query(swStTvmDailyBill)).getRecords();
        try {
            R<List<SysDictItem>> inputDataStatus = systemUserService.getDictByType(StmConstans.STM_INPUT_DATA_STATUS);
            List<SysDictItem> dictData = inputDataStatus.getData();
            if (CollectionUtil.isNotEmpty(records)) {
                Map<String, String> map = dictData.stream().collect(Collectors.toMap(SysDictItem::getValue, SysDictItem::getLabel));
                for (SwStTvmDailyBill record : records) {
                    record.setApprovalStatus(map.get(record.getApprovalStatus()));
                }
            }
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("TVM日结账单数据", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
            EasyExcel.write(response.getOutputStream(), SwStTvmDailyBill.class).
                    sheet("TVM日结账单数据").doWrite(records);
        } catch (IOException e) {
            log.error("导出TVM日结账单数据失败");
        }
    }

    /**
     * 新增或tvm日结数据
     *
     * @param swStTvmDailyBillDTO 新增或者修改tvm日结数据
     * @return R
     */
    @ApiOperation(value = "新增修改tvm日结数据", notes = "新增或者修改tvm日结数据")
    @SysLog("新增或者修改tvm日结数据")
    @PutMapping("/saveorupdate")
    @PreAuthorize("@pms.hasPermission('swsttvmdailybill_save_or_update')")
    public R saveOrUpdteSwStTvmDailyBill(@RequestBody SwStTvmDailyBillDTO swStTvmDailyBillDTO) {
        return R.ok(swStTvmDailyBillService.saveOrUpdteSwStTvmDailyBill(swStTvmDailyBillDTO));
    }

    /**
     * 修改tvm日结数据
     *
     * @param swStTvmDailyBillDTO 修改tvm日结数据
     * @return R
     */
    @ApiOperation(value = "修改tvm日结数据", notes = "修改tvm日结数据")
    @SysLog("修改tvm日结数据")
    @PutMapping("/update/pay")
    @PreAuthorize("@pms.hasPermission('swsttvmdailybill_update_pay')")
    public R updateOnePay(@RequestBody SwStTvmDailyBillDTO swStTvmDailyBillDTO) {
        return R.ok(swStTvmDailyBillService.updateOnePay(swStTvmDailyBillDTO));
    }


}
